package com.atguigu.springbootdemo.customer.service.impl;

import com.atguigu.springbootdemo.customer.bean.Customer;
import com.atguigu.springbootdemo.customer.mapper.CustomerMapper;
import com.atguigu.springbootdemo.customer.service.CustomerService;
import com.atguigu.springbootdemo.util.SqlUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ClassName: CustomerServiceImpl
 * Package: com.atguigu.springbootdemo.service.impl
 * Description:
 *
 * @Author:
 * @Create: 2024/3/13 09:05
 * @Version: 1.0
 */
@Service("csi")
@DS("test")
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    @Autowired
    CustomerMapper customerMapper;
    @Override
    public Customer getCustomer(Integer id) {
        // 1. 业务处理
        // 2. 调用数据层
        // 自己定义的mapper方法
//         return customerMapper.selectCustomerById(id);
        return customerMapper.selectById(id);
    }

    @Override
    public List<Customer> getCustomerList() {
        return customerMapper.getCustomerList();
    }

    @Override
    public void savaCustomer(Customer customer) {
//        customerMapper.insertCustomer(customer);
        customerMapper.insert(customer);
    }

    @Override
    public void updateCustomer(Customer customer) {
//        customerMapper.updateCustomerById(customer);
        customerMapper.updateById(customer);
    }

    @Override
    public void deleteCustomer(Integer id) {
//        customerMapper.deleteCustomerById(id);
        customerMapper.deleteById(id);

//        getBaseMapper().deleteById(id);
//        this.baseMapper.deleteById(id);
    }

    // 动态sql 自己拼接
    @Override
    public List<Customer> selectCustomerByCondition(String username, Integer age) {
        StringBuilder sql = new StringBuilder(" select id , username, age from customer where 1=1 ");

        if(username !=null && !username.trim().isEmpty()) {
            sql.append(" and username like '%").append(SqlUtil.filterUnsafeSql(username)).append("%' ");
        }
        if(age != null) {
            sql.append(" and age =").append(age);
        }

        return customerMapper.selectCustomersByUsernameAndAge(sql.toString());
    }
}
